import Vue from 'vue'
import App from './App.vue'
import router from './router.js'
import jv from './api/enums.js'
import axios from 'axios'
// import infiniteScroll from 'vue-infinite-scroll';
//
// Vue.use(infiniteScroll);
Vue.config.productionTip = false;

window.Server_Host = "http://localhost:7001";
//  window.Server_Host = "http://192.168.114.50:8001";
//window.Server_Host = "http://dev8.cn:8280";   //
window.Image_Host = "http://dev8.cn:8282";

(function (jv) {
    window.jv = jv;

    jv.initVue({vue:Vue,axios:axios,router:router});
    Vue.config.productionTip = true;

    function Radio() {
    }

    function Check() {
    }

    function Computed() {
    }

    //重复的，数据类型。
    function Repeatble() {
    }

    window.Radio = Radio;
    window.Check = Check;
    window.Computed = Computed;
    window.Repeatble = Repeatble;

    Vue.prototype.Radio = Radio;
    Vue.prototype.Check = Check;
    Vue.prototype.Computed = Computed;
    Vue.prototype.Repeatble = Repeatble;

    jv.reset = function () {
    };

    jv.debugger = function (v) {
        console.log(v);
    };

    // Vue.prototype.post =  Vue.prototype.$http.post;

    axios.interceptors.request.use(config => {
        //处理Java的布尔类型
        jv.recursionJson(config.data, (key1, value, target) => {

            if (value !== false && value !== true) {
                return;
            }

            //转为 isUpper 形式。
            if (key1.length > 2 && (key1.slice(0, 2) == "is" && key1.charCodeAt(2).Between(65, 90))) {
                var key2 = key1[0].toLowerCase() + key1.slice(1)
                if (key2 in target == false) {
                    target[key2] = value;
                    delete target[key1];
                }
            }
        });

        return config;
    }, error => {
        return Promise.reject(error);
    });


    axios.interceptors.response.use(response => {
        try {
            var data = response.body;
            if (data && jv.isPlainObject(data) && ((response.headers["content-type"] || "").indexOf("application/json") >= 0)) {
                jv.fillRes(data);

                //处理Java的布尔类型
                jv.recursionJson(data, (key1, value, target) => {

                    if (value !== false && value !== true) {
                        return;
                    }

                    //转为 isUpper 形式。
                    if (key1.length > 2 && (key1.slice(0, 2) == "is" && key1.charCodeAt(2).Between(65, 90))) {

                    } else {
                        var key2 = "is" + key1[0].toUpperCase() + key1.slice(1)
                        if (key2 in target == false) {
                            target[key2] = value;
                            delete target[key1];
                        }
                    }

                });
            }
        } catch (e) {
            console.error("axios.interceptors.response:" + e.message)
            return Promise.reject(e);
        }
        return response;
    }, error => {
        var resp = error.response;
        if (resp) {
            var status = resp.status;
            if (status == 401) {
                jv.main.loginFromVisible = true;
                return Promise.reject(error);
            }
        }
        return Promise.reject(error);
    });

    Vue.prototype.$http = axios;


    window.onerror = function (strMsg, url, line) {
        if (strMsg) {
            console.log(strMsg);
        }
    };

    jv.info = function (msg, title) {
        jv.pop_msg(msg, title, "info");
    };

    jv.warn = function (msg, title, opt) {
        jv.pop_msg(msg, title, "warn");
    };

    jv._last_error_msg = "";
    jv._last_error_title = "";
    jv.showLastError = function () {
        if (!jv._last_error_msg) return;
        return jv.error(jv._last_error_msg, jv._last_error_title);
    };

    jv.chk_clear = function (chk_opt) {
        if (chk_opt && chk_opt.target) {
            chk_opt.target.classList.remove("chk_error");
        } else {
            Array.from(document.body.getElementsByClassName("chk_error")).forEach(it => it.classList.remove("chk_error"));
        }
    };

    jv.chk_error = function (chk_opt) {
        if (!chk_opt || chk_opt.type != "chk") {
            return;
        }

        var msg = chk_opt.msg;
        if (!msg) {
            var kv = chk_opt.target.closest(".kv");
            if (kv) {
                msg = ((kv.getElementsByClassName("k")[0] || {}).textContent || "").trim() + " " + chk_opt.detail;
            }
        }

        // jv.chk_clear();
        chk_opt.target.classList.add("chk_error");
        console.error(msg2);
        //只提示第一个
        if (!chk_opt.index) {
            jv.pop_msg(msg, "数据校验失败", "chk");
        }
    };
    jv.error = function (msg, title, opt, chk_opt) {
        console.error(msg);

        jv._last_error_msg = msg;
        jv._last_error_title = title;

        // var ret = jv.main.$notify(Object.assign({
        //     title: title || '错误',
        //     message: msg,
        //     type: 'error',
        //     customClass: "popmsg error_msg"
        // }, opt));

        jv.pop_msg(msg, title, "error");


        if (chk_opt && chk_opt.type == "chk") {
            return false;
        }
        return ret;
    };

    jv.pop_msg = function (msg, title, type) {
        var msg2 = msg;
        if (title) {
            msg2 = "[" + title + "] " + "[" + type + "] " + msg2;
        }

        if (type in console) {
            console[type](msg2);
        }

        var p = document.getElementById("_pop_msg_root_");
        if (!p) {
            p = document.createElement("div");
            p.timer_number = 0;
            p.timerId = setInterval(function () {
                if (p.timer_number < 0 && p.timer_number >= 7) {
                    return;
                }

                p.timer_number++;
                if (p.timer_number >= 5) {
                    p.classList.remove("fade_in");
                    p.classList.add("fade_out");
                    return;
                }

            }, 1000);
            p.onmouseenter = function () {
                p.timer_number = -1;
            };
            p.onmouseleave = function () {
                p.timer_number = 0;
            };

            p.id = "_pop_msg_root_";
            p.classList.add("pop_msg");
            p.innerHTML = "<fieldset><legend></legend><div class='msg'></div></fieldset>";
            document.body.appendChild(p);
        }
        p.timer_number = 0;
        p.classList.remove("fade_in", "fade_out");

        p.getElementsByTagName("legend")[0].innerHTML = title;
        p.getElementsByClassName("msg")[0].innerHTML = msg;

        p.classList.add("fade_in");
    };

    jv.confirm = function (msg, buttons, opt) {
        console.log(title + ": " + msg)
    };

    jv.prompt = function (msg, title, opt) {
        console.log(title + ": " + msg)
    }
})(jv);


//https://www.jianshu.com/p/7dd126a7dc77
window.onscroll = function () {
    //console.log("onscroll");
    //文档内容实际高度（包括超出视窗的溢出部分）
    var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
    //滚动条滚动距离
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    //窗口可视范围高度
    var clientHeight = window.innerHeight || Math.min(document.documentElement.clientHeight, document.body.clientHeight);

    if (Math.ceil(clientHeight + scrollTop) >= Math.ceil(scrollHeight)) {
        if (jv.scroll2Bottom__startAt__ && (Date.now() - jv.scroll2Bottom__startAt__ < 500)) {
            return;
        }

        jv.scroll2Bottom__startAt__ = Date.now();

        jv.scroll2Bottom && jv.scroll2Bottom();
    }
};


(function (jv) {

    Object.defineProperties(window, {
        "Upload_Host": {
            get: function () {
                return this._Upload_Host;
            },
            set: function (val) {
                this._Upload_Host = val;
                Vue.prototype.Upload_Host = val;
            }
        }
    });

    // Vue.mixin({
    //     mounted() {
    //         if (this.$el) {
    //             var tagName = this.$options._componentTag;
    //             if (tagName == "el-autocomplete") {
    //                 this.$el.querySelectorAll(".el-input__inner").forEach(inner => {
    //                     Object.entries(inner.closest(".el-autocomplete").dataset).forEach(item => {
    //                         inner.dataset[item[0]] = item[1];
    //                     });
    //                 })
    //             }
    //         }
    //         if (jv && jv.loading) {
    //             jv.loading = false;
    //         }
    //     },
    //     beforeCreate() {
    //         var self = this;
    //         this["$resetData"] = function (key) {
    //             var data = jv.evalExpression(self.$data, key);
    //             var option = jv.evalExpression(self.$options.data(), key);
    //             if (!data.ok || option.ok) {
    //                 return;
    //             }
    //             return Object.assign(data.value, option.value);
    //         };
    //     }
    // });


    var vue = new Vue({
        router,
        // watch: {
        //     '$route'(to, from) {
        //         jv.loading = false;
        //     }
        // },
        render: h => h(App)
    }).$mount('#app');

    vue.$nextTick(it => {
        // jv.main.loadData();
        document.documentElement.classList.add("loaded");
    });

})(jv);
